from django.shortcuts import render

import hashlib

import datetime
from .models import User
from .models import ConfirmString
from django.conf import settings

from .forms import UserForm
from .forms import RegisterForm

# Create your views here.

from django.shortcuts import redirect

def index(requset):
    pass
    return render(requset, 'login/index.html')

def login(request):
    if request.session.get('is_login', None):
        return redirect("/index/")
    if request.method == "POST":
        login_form = UserForm(request.POST)
        message = "请检查填写的内容！"
        if login_form.is_valid():
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            try:
                user = User.objects.get(name=username)
                if not user.has_confirmed:
                    message = '该用户还没有通过邮件认证'
                    return render(request, 'login/confirm.html', locals())
                if user.password == hash_code(password): # 哈希值和数据库内的值进行比对
                    request.session['is_login'] = True
                    request.session['user_id'] = user.id
                    request.session['user_name'] = user.name
                    return redirect('/index/')
                else:
                    message = "密码不正确！"
            except:
                message = "用户不存在！"
    login_form = UserForm()
    return render(request, 'login/login.html', locals())

def register(request):
    if request.session.get('is_login', None):
        return redirect('/index/')
    if request.method == 'POST':
        register_form = RegisterForm(request.POST)
        message = '请检查填写的内容'
        if register_form.is_valid(): # 获取表单填写的数据
            username = register_form.cleaned_data['username']
            password1 = register_form.cleaned_data['password1']
            password2 = register_form.cleaned_data['password2']
            email = register_form.cleaned_data['email']
            sex = register_form.cleaned_data['sex']
            if password1 != password2: # 验证两次输入是否一致
                message = '两次输入的密码不一样'
                return render(request, 'login/register.html', locals())
            else:
                same_name_user = User.objects.filter(name=username)
                if same_name_user: # 如果用户名已经存在
                    message = '用户已经存在，请重新输入'
                    return render(request, 'login/register.html', locals())

                same_email_user = User.objects.filter(email=email)
                if same_email_user: # 如果用户名已经存在
                    message = '该邮箱已被注册，请使用其他邮箱'
                    return render(request, 'login/register.html', locals())

                # 当一切都ok， 则创建新用户
                new_user = User()
                new_user.name = username
                new_user.password = hash_code(password1)
                new_user.sex = sex
                new_user.save()

                # 创建确认码
                code = make_confirm_string(new_user)
                send_email(email, code)
                message = '请前往注册邮箱，进行注册确认'
                return render(request, 'login/confirm.html', locals())

    register_form = RegisterForm()
    return render(request, 'login/register.html', locals())

# 创建确认码
def make_confirm_string(user):
    now = datetime.datetime.now().strftime("%Y-%M-%D %H:%M:%S")
    code = hash_code(user.name, now)
    ConfirmString.objects.create(code=code, user=user)
    return code

# 发送邮件
def send_email(email, code):

    from django.core.mail import EmailMultiAlternatives

    subject = '来自BOSS商学的注册确认邮件'
    text_content = '感谢注册BOSS商学app，下载BOSS商学app碎片化学习总裁课程，若果你收到这条消息，说明你的邮箱服务器不提供HTML链接功能，请联系管理员。'
    html_content = '''
                    <p>感谢注册<a href="http://{}/confirm/?code={}" target=blank>www.bossapp.cn</a>，\
                    这是波士商学的官网</p>
                    <p>请点击站点链接完成注册确认！</p>
                    <p>此链接有效期为{}天！</p>
                    '''.format('127.0.0.1:8000', code, settings.CONFIRM_DAYS)
    msg = EmailMultiAlternatives(subject, text_content, settings.EMAIL_HOST_USER, [email])
    msg.attach_alternative(html_content, "text/html")
    msg.send()

def logout(requset):
    if not requset.session.get('is_login', None):
        return redirect('/index/')
    requset.session.flush()
    return redirect("/index/")

# 加密函数
def hash_code(s, salt='mysite'):
    h = hashlib.sha256()
    s += salt
    h.update(s.encode())  # update方法接收bytes类型
    return h.hexdigest()

def user_confirm(request):
    code = request.GET.get('code', None)
    message = ''
    try:
        confirm = ConfirmString.objects.get(code=code)
    except:
        message = '无效的请求'
        return render(request, 'login/confirm.html', locals())
    c_time = confirm.c_time
    now = datetime.datetime.now()

    if now > c_time + datetime.timedelta(settings.CONFIRM_DAYS):
        confirm.user.delete()
        message = '你的邮件已经过期，请重新注册'
        return render(request, 'login/register.html', locals())
    else:
        confirm.user.has_confirmed = True
        confirm.user.save()
        confirm.delete()
        message = '感谢确认，请使用账户登录'
        return render(request, 'login/login.html', locals())